import React, { useState, useEffect } from 'react';
import { ArrowLeft, Calendar, Clock, MapPin, Navigation, Utensils, Camera, Sun, CloudRain } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import NavigationLinks from '../components/NavigationLinks';

interface ItineraryDay {
  day: number;
  date: string;
  theme: string;
  weather_plan: string;
  total_duration: string;
  total_steps: string;
  activities: Activity[];
}

interface Activity {
  time: string;
  activity: string;
  location: string;
  duration: string;
  description: string;
  transport: string;
  cost: string;
  tips: string;
  photo_spots?: string[];
  recommended_food?: string[];
}

interface WeatherAlternatives {
  rainy_day_plan: {
    day1_alternatives: string[];
    day2_alternatives: string[];
  };
  hot_weather_plan: {
    adjustments: string[];
  };
}

const ItineraryPage: React.FC = () => {
  const navigate = useNavigate();
  const [itinerary, setItinerary] = useState<{ 
    days: ItineraryDay[];
    weather_alternatives: WeatherAlternatives;
    budget_breakdown: any;
    packing_suggestions: string[];
  } | null>(null);
  const [selectedDay, setSelectedDay] = useState(1);
  const [weatherPlan, setWeatherPlan] = useState<'sunny' | 'rainy'>('sunny');
  const [showNavigation, setShowNavigation] = useState(false);
  const [selectedRoute, setSelectedRoute] = useState<{
    start: { name: string; lat: number; lng: number };
    end: { name: string; lat: number; lng: number };
  } | null>(null);

  // 加载行程数据
  useEffect(() => {
    const loadItinerary = async () => {
      try {
        const response = await fetch('/src/data/itinerary.json');
        const data = await response.json();
        setItinerary(data.itinerary);
      } catch (error) {
        console.error('加载行程数据失败:', error);
      }
    };
    loadItinerary();
  }, []);

  // 获取活动图标
  const getActivityIcon = (activity: string) => {
    if (activity.includes('游览') || activity.includes('参观')) {
      return <MapPin className="text-red-500" size={18} />;
    } else if (activity.includes('餐') || activity.includes('食')) {
      return <Utensils className="text-green-500" size={18} />;
    } else if (activity.includes('拍照') || activity.includes('摄影')) {
      return <Camera className="text-orange-500" size={18} />;
    } else {
      return <Clock className="text-blue-500" size={18} />;
    }
  };

  // 处理导航请求
  const handleNavigation = (startLocation: string, endLocation: string) => {
    const locationCoords: { [key: string]: { lat: number; lng: number } } = {
      '南京南站': { lat: 31.9555, lng: 118.7134 },
      '总统府': { lat: 32.042578, lng: 118.796877 },
      '南京博物院': { lat: 32.041851, lng: 118.832977 },
      '老门东历史街区': { lat: 32.031234, lng: 118.789456 },
      '夫子庙': { lat: 32.034567, lng: 118.788123 },
      '玄武湖公园': { lat: 32.067890, lng: 118.787456 },
      '中山陵': { lat: 32.067778, lng: 118.843333 },
      '明孝陵': { lat: 32.058889, lng: 118.826667 }
    };

    const start = locationCoords[startLocation] || { lat: 32.0503, lng: 118.7969 };
    const end = locationCoords[endLocation] || { lat: 32.0503, lng: 118.7969 };

    setSelectedRoute({
      start: { name: startLocation, ...start },
      end: { name: endLocation, ...end }
    });
    setShowNavigation(true);
  };

  if (!itinerary) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">正在加载行程数据...</p>
        </div>
      </div>
    );
  }

  const currentDay = itinerary.days.find(day => day.day === selectedDay);

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 顶部导航栏 */}
      <div className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 py-4">
          <div className="flex items-center space-x-4">
            <button
              onClick={() => navigate('/')}
              className="flex items-center space-x-2 text-gray-600 hover:text-gray-800 transition-colors"
            >
              <ArrowLeft size={20} />
              <span>返回首页</span>
            </button>
            <div className="flex-1">
              <h1 className="text-2xl font-bold text-gray-800">详细行程规划</h1>
              <p className="text-gray-600">南京2日精华游完整攻略</p>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          {/* 左侧：行程详情 */}
          <div className="lg:col-span-3 space-y-6">
            {/* 天数和天气选择 */}
            <div className="bg-white rounded-lg shadow-md p-6">
              <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
                <div className="flex space-x-2">
                  {itinerary.days.map(day => (
                    <button
                      key={day.day}
                      onClick={() => setSelectedDay(day.day)}
                      className={`px-4 py-2 rounded-lg font-medium transition-colors ${
                        selectedDay === day.day
                          ? 'bg-blue-600 text-white'
                          : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                      }`}
                    >
                      第{day.day}天
                    </button>
                  ))}
                </div>
                <div className="flex items-center space-x-4">
                  <span className="text-sm font-medium text-gray-700">天气方案:</span>
                  <div className="flex space-x-2">
                    <button
                      onClick={() => setWeatherPlan('sunny')}
                      className={`flex items-center space-x-1 px-3 py-1 rounded-lg text-sm transition-colors ${
                        weatherPlan === 'sunny'
                          ? 'bg-yellow-100 text-yellow-800'
                          : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                      }`}
                    >
                      <Sun size={14} />
                      <span>晴天</span>
                    </button>
                    <button
                      onClick={() => setWeatherPlan('rainy')}
                      className={`flex items-center space-x-1 px-3 py-1 rounded-lg text-sm transition-colors ${
                        weatherPlan === 'rainy'
                          ? 'bg-blue-100 text-blue-800'
                          : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                      }`}
                    >
                      <CloudRain size={14} />
                      <span>雨天</span>
                    </button>
                  </div>
                </div>
              </div>
            </div>

            {/* 天气备选方案提示 */}
            {weatherPlan === 'rainy' && (
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <h3 className="font-semibold text-blue-800 mb-2">雨天备选方案</h3>
                <div className="text-sm text-blue-700">
                  <p className="mb-2">第1天备选路线:</p>
                  <p className="mb-3">{itinerary.weather_alternatives.rainy_day_plan.day1_alternatives[0]}</p>
                  <p className="mb-2">第2天备选路线:</p>
                  <p>{itinerary.weather_alternatives.rainy_day_plan.day2_alternatives[0]}</p>
                </div>
              </div>
            )}

            {/* 当日行程详情 */}
            {currentDay && (
              <div className="bg-white rounded-lg shadow-md p-6">
                <div className="mb-6">
                  <div className="flex items-center justify-between mb-4">
                    <h2 className="text-2xl font-bold text-gray-800">
                      第{currentDay.day}天 - {currentDay.theme}
                    </h2>
                    <div className="text-sm text-gray-500">
                      {currentDay.date}
                    </div>
                  </div>
                  
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4 p-4 bg-gray-50 rounded-lg">
                    <div className="flex items-center space-x-2">
                      <Calendar size={16} className="text-blue-600" />
                      <div>
                        <p className="text-xs text-gray-500">总时长</p>
                        <p className="font-medium">{currentDay.total_duration}</p>
                      </div>
                    </div>
                    <div className="flex items-center space-x-2">
                      <MapPin size={16} className="text-red-600" />
                      <div>
                        <p className="text-xs text-gray-500">步数</p>
                        <p className="font-medium">{currentDay.total_steps}</p>
                      </div>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Clock size={16} className="text-green-600" />
                      <div>
                        <p className="text-xs text-gray-500">活动数</p>
                        <p className="font-medium">{currentDay.activities.length}个</p>
                      </div>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Sun size={16} className="text-yellow-600" />
                      <div>
                        <p className="text-xs text-gray-500">方案</p>
                        <p className="font-medium">{currentDay.weather_plan}</p>
                      </div>
                    </div>
                  </div>
                </div>

                {/* 活动时间轴 */}
                <div className="space-y-6">
                  {currentDay.activities.map((activity, index) => (
                    <div key={index} className="flex space-x-4">
                      <div className="flex flex-col items-center">
                        <div className="w-12 h-12 bg-white border-2 border-blue-200 rounded-full flex items-center justify-center shadow-sm">
                          {getActivityIcon(activity.activity)}
                        </div>
                        {index < currentDay.activities.length - 1 && (
                          <div className="w-0.5 h-20 bg-gray-200 mt-4"></div>
                        )}
                      </div>
                      
                      <div className="flex-1 pb-8">
                        <div className="bg-white border border-gray-200 rounded-lg p-6 hover:shadow-lg transition-shadow">
                          <div className="flex items-start justify-between mb-3">
                            <div>
                              <h3 className="text-lg font-semibold text-gray-800 mb-1">
                                {activity.activity}
                              </h3>
                              <div className="flex items-center space-x-4 text-sm text-gray-600">
                                <span className="flex items-center space-x-1">
                                  <Clock size={14} />
                                  <span>{activity.time}</span>
                                </span>
                                <span className="flex items-center space-x-1">
                                  <MapPin size={14} />
                                  <span>{activity.location}</span>
                                </span>
                              </div>
                            </div>
                            <div className="text-right">
                              <div className="text-sm font-medium text-gray-800">
                                {activity.duration}
                              </div>
                              <div className="text-sm text-gray-600">
                                {activity.cost}
                              </div>
                            </div>
                          </div>
                          
                          <p className="text-gray-700 mb-4">{activity.description}</p>
                          
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                            <div>
                              <span className="text-sm font-medium text-gray-700">交通方式:</span>
                              <p className="text-sm text-gray-600 mt-1">{activity.transport}</p>
                            </div>
                            <div className="flex items-center">
                              <button
                                onClick={() => handleNavigation(activity.location, currentDay.activities[index + 1]?.location || activity.location)}
                                className="flex items-center space-x-2 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
                              >
                                <Navigation size={16} />
                                <span>导航到此地</span>
                              </button>
                            </div>
                          </div>
                          
                          {activity.tips && (
                            <div className="mb-4 p-3 bg-yellow-50 border-l-4 border-yellow-400 rounded">
                              <p className="text-sm text-yellow-800">
                                <span className="font-medium">💡 贴士:</span> {activity.tips}
                              </p>
                            </div>
                          )}
                          
                          {activity.recommended_food && (
                            <div className="mb-4">
                              <span className="text-sm font-medium text-gray-700 mb-2 block">🍜 推荐美食:</span>
                              <div className="flex flex-wrap gap-2">
                                {activity.recommended_food.map((food, idx) => (
                                  <span key={idx} className="px-3 py-1 bg-green-100 text-green-800 text-sm rounded-full">
                                    {food}
                                  </span>
                                ))}
                              </div>
                            </div>
                          )}
                          
                          {activity.photo_spots && (
                            <div>
                              <span className="text-sm font-medium text-gray-700 mb-2 block">📸 拍照点:</span>
                              <div className="flex flex-wrap gap-2">
                                {activity.photo_spots.map((spot, idx) => (
                                  <span key={idx} className="px-3 py-1 bg-orange-100 text-orange-800 text-sm rounded-full">
                                    {spot}
                                  </span>
                                ))}
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* 右侧：导航和信息面板 */}
          <div className="space-y-6">
            {/* 导航面板 */}
            {showNavigation && selectedRoute && (
              <NavigationLinks
                startPoint={selectedRoute.start}
                endPoint={selectedRoute.end}
                className=""
              />
            )}

            {/* 预算明细 */}
            <div className="bg-white rounded-lg shadow-md p-6">
              <h3 className="font-bold text-lg text-gray-800 mb-4">💰 预算明细</h3>
              <div className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <span className="text-gray-600">交通费用</span>
                  <span className="font-medium">{itinerary.budget_breakdown.transportation}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">门票费用</span>
                  <span className="font-medium">{itinerary.budget_breakdown.tickets}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">餐饮费用</span>
                  <span className="font-medium">{itinerary.budget_breakdown.food}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">购物费用</span>
                  <span className="font-medium">{itinerary.budget_breakdown.shopping}</span>
                </div>
                <div className="border-t pt-2 mt-2">
                  <div className="flex justify-between font-semibold">
                    <span>总计</span>
                    <span className="text-blue-600">400-600元/人</span>
                  </div>
                </div>
              </div>
            </div>

            {/* 打包建议 */}
            <div className="bg-white rounded-lg shadow-md p-6">
              <h3 className="font-bold text-lg text-gray-800 mb-4">🎒 打包建议</h3>
              <div className="space-y-2">
                {itinerary.packing_suggestions.map((item, index) => (
                  <div key={index} className="flex items-center space-x-2 text-sm">
                    <div className="w-2 h-2 bg-blue-600 rounded-full"></div>
                    <span className="text-gray-700">{item}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* 天气调整建议 */}
            <div className="bg-white rounded-lg shadow-md p-6">
              <h3 className="font-bold text-lg text-gray-800 mb-4">🌤️ 天气调整</h3>
              <div className="space-y-2 text-sm">
                {itinerary.weather_alternatives.hot_weather_plan.adjustments.map((adjustment, index) => (
                  <div key={index} className="flex items-start space-x-2">
                    <div className="w-2 h-2 bg-orange-500 rounded-full mt-1.5"></div>
                    <span className="text-gray-700">{adjustment}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ItineraryPage;